package com.duobaoyu.dby.supply.biz.util;

import com.duobaoyu.dby.channel.common.util.SpringContextHolderUtils;
import com.duobaoyu.dby.common.core.util.SpringContextHolder;
import com.duobaoyu.dby.common.mybatis.config.IdGeneratorSnowflake;
import com.duobaoyu.dby.supply.biz.client.resource.ResourceApiClient;
import com.duobaoyu.dby.supply.biz.client.resource.bean.bo.BusinessConfigBO;
import com.duobaoyu.dby.supply.core.common.exception.CustomAssert;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import java.util.Optional;

/**
 * @author liyang
 * @version 1.0.0
 * @ClassName IdGeneratorUtil
 * @Description 供应链平台ID生成
 * @createTime 16:33:00 2022/05/16
 */
@Slf4j
@UtilityClass
public class IdGeneratorUtil {

    /**
     * 实物详情单订单号生成
     * 渠道代码+业务代码+唯一值
     *
     * @param code ChannelCodeEnum.code
     * @param bizCode serverName # BizCodeEnum.val
     * @return
     */
    public String getOrderSn(String code, String bizCode) {
        return getOrderCode(code, bizCode);
    }

	/**
	 * 总单号生成
	 * @param bizCode 业务编码
	 * @return String tradeSn
	 */
	public String getSupplyTradeSn(String bizCode) {
		IdGeneratorSnowflake snowflake = SpringContextHolder.getBean(IdGeneratorSnowflake.class);
		ResourceApiClient resourceApiClient = SpringContextHolderUtils.getBean(ResourceApiClient.class);
		BusinessConfigBO bizCodeInfo = resourceApiClient.getBizCodeInfo(bizCode);
		String bizNumber = Optional.ofNullable(bizCodeInfo.getOrderSnPrefix()).orElse("00");
		return bizNumber.concat(String.valueOf(snowflake.snowflakeId()));
	}

	/**
	 * code 生成
	 * @param code code编码
	 * @param bizCode 业务编码
	 * @return String 订单号
	 */
    private String getOrderCode(String code, String bizCode) {
		CustomAssert.hasLength(code,"编号不能为空");
		ResourceApiClient resourceApiClient = SpringContextHolderUtils.getBean(ResourceApiClient.class);
		BusinessConfigBO bizCodeInfo = resourceApiClient.getBizCodeInfo(bizCode);
		String bizNumber = Optional.ofNullable(bizCodeInfo.getOrderSnPrefix()).orElse("00");
        IdGeneratorSnowflake snowflake = SpringContextHolder.getBean(IdGeneratorSnowflake.class);
        return code.concat(bizNumber).concat(String.valueOf(snowflake.snowflakeId()));
    }


	/**
	 * 售后申请编号
	 * 渠道代码+业务代码+ 售后（7） +唯一值
	 * @param code ChannelCodeEnum.code
	 * @param bizCode serverName # BizCodeEnum.val
	 * @return
	 */
	public String getAfterSaleCode(String code,String bizCode) {
		return getOrderCode(code, bizCode);
	}

}
